package com.xmy.study.controller;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.toolkit.StringUtils;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.xmy.study.entity.*;
import com.xmy.study.service.*;
import com.xmy.study.util.Code;
import com.xmy.study.util.ExcelExportHandle;
import com.xmy.study.util.PageResult;
import com.xmy.study.util.Result;
import io.swagger.annotations.ApiImplicitParam;
import io.swagger.annotations.ApiImplicitParams;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.context.annotation.Lazy;
import org.springframework.web.bind.annotation.*;

import java.util.Map;

@RestController
@RequestMapping("/api/admin/chaPlan")
public class ChaPlanController {
    @Autowired
    @Lazy
    IChaPlanService iChaPlanService;

    @Autowired
    @Lazy
    IAdmOrganizationService iAdmOrganizationService;

    @Autowired
    @Lazy
    IStudentService iStudentService;

    @Autowired
    @Lazy
    IEduClassTypeService iEduClassTypeService;

    @Autowired
    @Lazy
    IEduVersionService iEduVersionService;

    @Autowired
    IDictService iDictService;

    @GetMapping("list")
    @ApiOperation("列表")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "schoolId", value = "校区", required = false, dataType = "String"),
            @ApiImplicitParam(name = "yearPart", value = "年份", required = false, dataType = "String"),
            @ApiImplicitParam(name = "quarterNum", value = "季度(学期)", required = false, dataType = "String"),
            @ApiImplicitParam(name = "yearClassId", value = "年级id", required = false, dataType = "String"),
            @ApiImplicitParam(name = "classTypeId", value = "班型id", required = false, dataType = "String"),
//            @ApiImplicitParam(name = "state", value = "状态", required = false, dataType = "String"),
            @ApiImplicitParam(name = "lessonNum", value = "学习到的课次", required = false, dataType = "String"),
            @ApiImplicitParam(name = "courseVersionId", value = "版本", required = false, dataType = "String"),
            @ApiImplicitParam(name = "brushCount", value = "刷题次数", required = false, dataType = "String")
    })
    public Result getList(@RequestParam Map<String, String> reMap,
                          @RequestParam(value = "isExport", required = false, defaultValue = "0") Integer isExport,// 是否为导出，1是0否
                          @RequestParam(value = "taskCategoryId", defaultValue = "1", required = false) String taskCategoryId) {
        int pageNum = reMap.get("pageNum") != null && !reMap.get("pageNum").isEmpty() ? Integer.parseInt(reMap.get("pageNum")) : 1;
        int pageSize = reMap.get("pageSize") != null && !reMap.get("pageSize").isEmpty() ? Integer.parseInt(reMap.get("pageSize")) : 10;
        Page<ChaPlan> iPage = new Page<>(pageNum, pageSize);

        String schoolId = reMap.get("schoolId");
        String yearPart = reMap.get("yearPart");
        String quarterNum = reMap.get("quarterNum");
        String yearClassId = reMap.get("yearClassId");
        String classTypeId = reMap.get("classTypeId");
//        String state = reMap.get("state");
        String lessonNum = reMap.get("lessonNum");
        String courseVersionId = reMap.get("courseVersionId");
        String subjectsId = reMap.get("subjectsId");
        String studentName = reMap.get("studentName");
        String brushCount = reMap.get("brushCount");

        QueryWrapper<ChaPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.select("*,(SELECT student_name FROM per_student_account WHERE deleted = 0 AND student_id = cha_plan.student_id LIMIT 1) AS studentName");
        queryWrapper.eq(StringUtils.isNotBlank(schoolId), "school_id", schoolId);
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.eq(StringUtils.isNotBlank(courseVersionId), "course_version_id", courseVersionId);
        queryWrapper.eq(StringUtils.isNotBlank(yearClassId), "year_class_id", yearClassId);
//        queryWrapper.eq(StringUtils.isNotBlank(state), "state", state);
        queryWrapper.eq(StringUtils.isNotBlank(classTypeId), "class_type_id", classTypeId);
        queryWrapper.eq(StringUtils.isNotBlank(lessonNum), "lesson_num", lessonNum);
        queryWrapper.eq(StringUtils.isNotBlank(subjectsId), "subjects_id", subjectsId);
        queryWrapper.inSql(StringUtils.isNotBlank(studentName), "student_id", "SELECT student_id FROM per_student_account WHERE deleted = 0 AND student_name LIKE '%" + studentName + "%'");
        queryWrapper.eq(StringUtils.isNotBlank(brushCount), "brush_count", brushCount);
        queryWrapper.eq(StringUtils.isNotBlank(taskCategoryId), "task_category_id", taskCategoryId);
        queryWrapper.orderByDesc("id");
        iChaPlanService.page(iPage, queryWrapper);

        for (ChaPlan chaPlan : iPage.getRecords()) {
            //校区名称
            AdmOrganization admOrganizationServiceById = iAdmOrganizationService.getById(chaPlan.getSchoolId());
            if (admOrganizationServiceById != null) {
                chaPlan.setSchoolName(admOrganizationServiceById.getName());
            }
            //学生名称
//            Student studentServiceById = iStudentService.getById(chaPlan.getStudentId());
//            if (studentServiceById != null) {
//                chaPlan.setStudentName(studentServiceById.getName());
//            }
            //班级名称
            EduClassType eduClassTypeServiceById = iEduClassTypeService.getById(chaPlan.getClassTypeId());
            if (eduClassTypeServiceById != null) {
                chaPlan.setClassTypeName(eduClassTypeServiceById.getName());
            }
            //版本名称
            EduVersion eduVersionServiceById = iEduVersionService.getById(chaPlan.getCourseVersionId());
            if (eduVersionServiceById != null) {
                chaPlan.setCourseVersionName(eduVersionServiceById.getName());
            }
            String categryName = iDictService.getDictNameByNumAndType(chaPlan.getTaskCategoryId(), 20);
            chaPlan.setTaskCategoryName(categryName);

            chaPlan.setYearClassStr(iDictService.getDictNameByNumAndType(chaPlan.getYearClassId(), 1));
        }

//        if (isExport == 1) {
//            ExcelExportHandle.export(response, "学习记录", iPage.getRecords(), ChaPlan.class);
//
//        }

        return new Result(Code.GET_OK, new PageResult<>(iPage.getRecords(), iPage.getTotal(), iPage.getPages()), Code.GET_OK_MSG);
    }

    @PostMapping("edit")
    @ApiOperation("修改")
    public Result edit(@RequestBody ChaPlan chaPlan) {
        if ((chaPlan.getRightNum() == null && chaPlan.getAmendNum() == null) || chaPlan.getId() == null) {
            return new Result(Code.ERROR, null, "请正确传参!");
        }

        UpdateWrapper<ChaPlan> chaPlanUpdateWrapper = new UpdateWrapper<>();
        chaPlanUpdateWrapper.eq("id", chaPlan.getId());
        if (chaPlan.getRightNum() != null) {
            chaPlanUpdateWrapper.set("right_num", chaPlan.getRightNum());
        }
        if (chaPlan.getAmendNum() != null) {
            chaPlanUpdateWrapper.set("amend_num", chaPlan.getAmendNum());
        }
        if (chaPlan.getBrushCount() != null) {
            chaPlanUpdateWrapper.set("brush_count", chaPlan.getBrushCount());
        }
        iChaPlanService.update(null, chaPlanUpdateWrapper);
        return new Result(Code.OK, null, Code.OK_MSG);
    }

    @GetMapping("getBrushCountMax")
    @ApiOperation("刷题次数最大值")
    @ApiImplicitParams({
            @ApiImplicitParam(name = "yearPart", value = "年份", required = true, dataType = "String"),
            @ApiImplicitParam(name = "quarterNum", value = "季度(学期)", required = true, dataType = "String")
    })
    public Result getBrushCountMax(@RequestParam Map<String, String> reMap) {
        String yearPart = reMap.get("yearPart");
        String quarterNum = reMap.get("quarterNum");

        QueryWrapper<ChaPlan> queryWrapper = new QueryWrapper<>();
        queryWrapper.eq(StringUtils.isNotBlank(yearPart), "year_part", yearPart);
        queryWrapper.eq(StringUtils.isNotBlank(quarterNum), "quarter_num", quarterNum);
        queryWrapper.orderByDesc("brush_count");
        queryWrapper.last("limit 1");
        ChaPlan one = iChaPlanService.getOne(queryWrapper);

        return new Result(Code.GET_OK, one, Code.GET_OK_MSG);
    }

    @DeleteMapping("delChaPlan")
    @ApiOperation("删除")
    public Result delChaPlan(@RequestParam Map<String, String> reMap) {
        if (reMap.get("id") == null || reMap.get("id").isEmpty()) {
            return new Result(Code.ERROR, "", "id不能为空！");
        }
        String[] ids = reMap.get("id").split(",");
        if (ids.length == 0) {
            return new Result(Code.ERROR, "", "id不能为空！");
        }
        for (String idFor : ids) {
            Long id = Long.valueOf(idFor);
            ChaPlan one = iChaPlanService.getById(id);
            if (one != null) {
                iChaPlanService.removeById(id);
                if (one.getIsFirst() == 1) {//第一条
                    ChaPlan planServiceOne = iChaPlanService.getOne(new QueryWrapper<ChaPlan>()
                            .eq("student_id", one.getStudentId())
                            .eq("year_part", one.getYearPart())
                            .eq("quarter_num", one.getQuarterNum())
                            .eq("class_type_id", one.getClassTypeId())
                            .eq("course_version_id", one.getCourseVersionId())
                            .eq("lesson_num", one.getLessonNum())
                            .eq("task_category_id", one.getTaskCategoryId())
                            .ne("id", id).orderByAsc("created_at").last("limit 1"));
                    if (planServiceOne != null) {
                        planServiceOne.setIsFirst(1);
                        iChaPlanService.updateById(planServiceOne);
                    }
                }
                if (one.getIsLast() == 1) {//最后一条
                    ChaPlan planServiceOne = iChaPlanService.getOne(new QueryWrapper<ChaPlan>()
                            .eq("student_id", one.getStudentId())
                            .eq("year_part", one.getYearPart())
                            .eq("quarter_num", one.getQuarterNum())
                            .eq("class_type_id", one.getClassTypeId())
                            .eq("course_version_id", one.getCourseVersionId())
                            .eq("lesson_num", one.getLessonNum())
                            .ne("id", id).orderByDesc("created_at").last("limit 1"));
                    if (planServiceOne != null) {
                        planServiceOne.setIsLast(1);
                        iChaPlanService.updateById(planServiceOne);
                    }
                }
            }
        }
        return new Result(Code.GET_OK, "", Code.DELETE_OK_MSG);
    }


}
